package com.phone580.app.model;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public abstract class BaseModel {

	protected String getContent(Element root, String name) {
		NodeList nodes = root.getElementsByTagName(name);
		if (nodes.getLength() > 0) {
			if (nodes.item(0).getNodeType() == Node.ELEMENT_NODE
					&& nodes.item(0).hasChildNodes())
				return nodes.item(0).getChildNodes().item(0).getNodeValue();
		}
		return "";
	}

	protected String getAttrValue(Element root, String name, String attrName) {
		NodeList nodes = root.getElementsByTagName(name);
		if (nodes.getLength() > 0) {
			Element element = (Element) nodes.item(0);
			if (element.hasAttribute(attrName)) {
				return element.getAttribute(attrName);
			}
		}
		if (root.getTagName().equalsIgnoreCase(name)) {
			return root.getAttribute(attrName);
		}
		return "";
	}
	
	protected Element getDomRootElement(String xml) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document dom = builder.parse(new InputSource(new StringReader(xml)));
		Element root = dom.getDocumentElement();
		return root;
	}
	
}
